package com.aauedu.springboot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//创建自定义拦截器
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //目标方法执行前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("LoginInterceptor的preHandle方法执行了~~");
        //看到访问的URI
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();
        log.info("preHandle拦截器请求到的URI:{}", requestURI);  //URI：去除localhost、port的资源路径  只输出了/monster.html  统一资源标识符
        log.info("preHandle拦截器请求到的URL:{}", requestURL);  //URL：http://localhost:8080/monster.html  统一资源定位符
        //进行登录校验
        HttpSession session = request.getSession();
        Object loginAdmin = session.getAttribute("loginAdmin");
        if (loginAdmin != null) {  //该用户已经登录成功
            //放行
            return true;
        } else {
            //拦截，重新返回到登录页面
            request.setAttribute("msg", "您还没有登录，请登录后重试~");
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle方法执行了~~");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion方法执行了~~");

    }
}
